package com.aaa.pro.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;

/**
 * fileName:OrderNumber
 * description:
 * author:JH
 * createTime:2020/4/18 20:24
 * version:1.0.0
 */
public class OrderNumber {
    // 私有的构造函数，保证外类不能实例化本类
    private OrderNumber() {};
    // 创建一个空实例对象，类需要用的时候才赋值
    private static OrderNumber instance = null;
    // 单例模式--懒汉模式
    public static synchronized OrderNumber getInstance(){
        if (instance==null){
            instance=new OrderNumber();
        }
        return instance;
    }
    private static int count=1;

    private static  final SimpleDateFormat sdf = new SimpleDateFormat(("yyyyMMddHHmmss"));

    private static String getNowDateStr(){
        return sdf.format(new Date());
    }

    private static String now = null;

    private final static ReentrantLock lock = new ReentrantLock();

    public static String GetRandom(Object i){
        String Newnumber= null;
        String dataStr = getNowDateStr();
        lock.lock();

        if (dataStr.equals(now)){
            try {
                if ((count>=10000)){
                    count = 1;
                }
                if(count<10){
                    Newnumber = i+"-"+getNowDateStr()+"000"+count;
                }else if(count<100){
                    Newnumber = i+"-"+getNowDateStr()+"00"+count;
                }
                else if(count<1000){
                    Newnumber = i+"-"+getNowDateStr()+"0"+count;
                }
            }finally {
                lock.unlock();
            }
        }
        else{
            count=1;
            now = getNowDateStr();
            try {
                if (count >= 10000)
                {
                    count = 1;
                }
                if (count<10) {
                    Newnumber = i+"-" + getNowDateStr()+"000"+count;
                }else if (count<100) {
                    Newnumber = i+"-" + getNowDateStr()+"00"+count;
                }else if(count<1000){
                    Newnumber = i+"-" + getNowDateStr()+"0"+count;
                }else  {
                    Newnumber = i+"-" + getNowDateStr()+count;
                }
                count++;
            }finally {
                lock.unlock();
            }
        }
        return Newnumber;
    }
}
